// 检查用户认证状态
async function checkAuth() {
    try {
        const response = await fetch('/api/check-auth');
        const data = await response.json();
        
        if (data.authenticated) {
            return true;
        } else {
            // 如果未登录且不在登录页面，重定向到登录页面
            if (!window.location.pathname.includes('login.html')) {
                window.location.href = '/login.html';
            }
            return false;
        }
    } catch (error) {
        console.error('认证检查失败:', error);
        showMessage('auth-message', '认证检查失败，请刷新页面重试', true);
        return false;
    }
}

// 退出登录
async function logout() {
    try {
        const response = await fetch('/api/logout', {
            method: 'POST'
        });
        
        if (response.ok) {
            window.location.href = '/login.html';
        } else {
            const data = await response.json();
            showMessage('auth-message', data.error || '退出失败', true);
        }
    } catch (error) {
        console.error('退出失败:', error);
        showMessage('auth-message', '退出失败，请重试', true);
    }
}

// 显示消息
function showMessage(elementId, message, isError = false) {
    const element = document.getElementById(elementId);
    if (element) {
        element.textContent = message;
        element.className = `message ${isError ? 'message-error' : 'message-success'}`;
        element.style.display = 'block';
        
        // 3秒后自动隐藏
        setTimeout(() => {
            element.style.display = 'none';
        }, 3000);
    }
}

// 页面加载完成后检查认证状态
document.addEventListener('DOMContentLoaded', () => {
    checkAuth();
}); 